import {
  lhRequest
} from "./index"
import {
  baseURL
} from "./config"
const App = getApp()

/**
 * 检查小程序session_key是否失效
 *    失效: 重新登录
 *    未失效: 检查loginkey是否失效
 *        失效: 重新登录
 */
export function checkSessionLogin() {
  wx.p.checkSession()
    .then((res) => {
      console.log("session_key 有效，可继续使用", res)
      if (wx.getStorageSync('loginkey') && wx.getStorageSync('infer_time')) {
        let operate_step = wx.getStorageSync('operate_step')
        if (operate_step == 1 || operate_step == 2) {
          wx.p.navigateTo({
            url: '/pages/capture/capture'
          }).then(() => {
            if (operate_step == 2) {
              wx.p.navigateTo({
                url: '/pages/userInfo-fill/userInfo-fill'
              })
            }
          })
        } else if (operate_step == 3) {
          wx.p.reLaunch({
            url: '/pages/diag-pay/diag-pay'
          })
        }
      } else {
        loadingLogin()
      }
    }).catch((res) => {
      console.log("session_key 失效，重新登录", res)
      loadingLogin()
    })
}


export async function loadingLogin() {
  await wx.p.showLoading({
    title: '加载中',
    mask: true
  })
  await login()
  await wx.p.hideLoading()
}
/**
 * 登录并登录密钥
 * @param {*} code 
 */
export async function login() {
  console.log("登录并获取loginkey")
  try {
    let res = await wx.p.login()
    res = await wx.p.request({
      url: baseURL + 'auth',
      method: 'POST',
      data: {
        "code": res.code
      }
    })
    if (res.data.message == 'success') {
      let data = res.data.data
      wx.setStorageSync('loginkey', data.loginkey)
      wx.setStorageSync('infer_time', data.infer_time * 1000)
      if (data.mobile) {
        wx.setStorageSync('mobile', data.mobile)
        getCurrentPages()[0].setData({
          mobile: data.mobile
        })
      }
      await wx.p.hideLoading()
      return data.loginkey
    } else {
      await App.showNetError()
    }
  } catch (err) {
    await App.showNetError()
  }
}

/**
 * 小程序获取手机号
 * @param {object} e - 按钮返回结果 <button open-type="getPhoneNumber">
 * @param {func} resolve - 成功执行
 */
export function getPhoneNumber(e, resolve) {
  let mobile = wx.getStorageSync('mobile')
  if (mobile) {
    resolve(mobile)
  } else if (e.detail.errMsg === 'getPhoneNumber:ok') {
    lhRequest.post({
      url: "get_mobile",
      data: {
        "loginkey": wx.getStorageSync('loginkey'),
        "phoneCode": e.detail.code
      },
      lhRequest_options: { //请求配置
        isShowLoad: true, //是否显示加载中(true)
        isErrorRetryRequest: true, //是否失败重新执行请求(false)
        requstTitle: "获取手机号" //请求提示标题('请求')
      }
    }, async (data) => {
      wx.setStorageSync('mobile', data.mobile)
      await resolve(data.mobile)
    })
  } else {
    wx.p.showToast({
      title: '手机号未授权',
      icon: 'none'
    });
  }
}